package com.haredot.controller;

import com.haredot.dto.PermissionTree;
import com.haredot.entity.Role;
import com.haredot.service.RoleService;
import com.haredot.utils.ValidUtils;
import com.haredot.vo.PageVo;
import com.haredot.vo.R;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Resource
    private RoleService roleService ;

    @PostMapping("/add")
    @PreAuthorize("hasAuthority('role:add')")
    public R<?> addRole(@RequestBody @Validated Role role, BindingResult bindingResult) {
        return ValidUtils.toResult(bindingResult, ()-> roleService.saveRole(role));
    }

    @PutMapping("/update/{id}")
    @PreAuthorize("hasAuthority('role:update')")
    public R<?> addRole(@PathVariable("id") Long id , @RequestBody @Validated Role role, BindingResult bindingResult) {
        role.setId(id);
        return ValidUtils.toResult(bindingResult, ()-> roleService.updateRole(role));
    }

    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('role:delete')")
    public R<?> removeRole(@PathVariable("id") Long id) {
        return roleService.removeRole(id);
    }

    @DeleteMapping("/batchRemove")
    @PreAuthorize("hasAuthority('role:batch:remove')")
    public R<?> removeRole(@RequestBody List<Long> roleIds) {
        return roleService.batchRemoveRoles(roleIds);
    }

    @GetMapping("/list")
    @PreAuthorize("hasAnyAuthority('role:query', 'role')")
    public R<PageVo> list(@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                          @RequestParam(value = "rows", required = false, defaultValue = "10")Integer rows,
                          @RequestParam  Map<String, Object> searchParams) {

        PageVo pageVo = new PageVo(page, rows);

        return roleService.queryRolesByPage(pageVo, searchParams);
    }

    @GetMapping("/{roleId}/queryPermissionTree")
    @PreAuthorize("hasAuthority('role:apply:permission')")
    public R<PermissionTree> queryPermissionTree(@PathVariable Long roleId) {

        return roleService.queryPermissionTree(roleId) ;
    }

    @PostMapping("/{roleId}/bindPermission")
    @PreAuthorize("hasAuthority('role:apply:permission')")
    public R<?> bindPermission(@PathVariable Long roleId, @RequestBody List<PermissionTree> nodes) {

        return roleService.bindPermission(roleId, nodes) ;
    }
}
